<template>
  <el-row class="box main-box bg-color">
    <el-col :span="12" class="h100">
      <h3>分类榜单</h3>
      <div class="music-menu df fw-w scrollable">
        <span
          class="menu-item"
          v-for="item in musicMenuList"
          :key="item.coverImgId"
          @click="goMenuMusicInfo(item)">
          <img :src="item.coverImgUrl" alt="" />
        </span>
      </div>
    </el-col>
    <el-col :span="12" class="h100">
      <h3>{{ currentMusicMenu.name }}</h3>
      <div style="padding: 0 15px; margin: 10px 0 15px 0">
        <div class="music-list df">
          <span class="f1">歌曲</span>
          <span class="f1">作者</span>
          <span style="color: transparent; padding-left: 20px">+</span>
        </div>
      </div>
      <div class="music-menu-list scrollable" ref="detailList" @scroll="handleScroll">
        <div class="music-list df" v-for="(item, index) in musicMenuDetailList" :key="item.id">
          <span class="music-name font-hide f1" @click="audioPlay(item, index)">
            {{ item.name }}
          </span>
          <span class="music-author font-hide f1">{{ item.ar[0].name }}</span>
          <span class="music-icon">+</span>
        </div>
      </div>
    </el-col>
  </el-row>
  <div class="progress-bar main-box">
    <el-slider
      v-model="progressValue"
      size="small"
      :max="progressMax"
      :format-tooltip="toTime"
      @change="progressChange" />
  </div>
  <div class="audio-box main-box">
    <div class="audio-info">
      <img :class="{ imgRotate: isAudioStart }" :src="currentImg" alt="" />
      <div class="info df fd-c">
        <span class="text-overflow">{{ currentName }}</span>
        <span class="text-overflow">{{ currentAuth }}</span>
      </div>
    </div>
    <div class="play">
      <el-icon class="icon" :size="playIconSize" color="#409EFC" @click="prevAudio">
        <i-ep-CaretLeft />
      </el-icon>
      <el-icon class="icon" :size="playIconSize" color="#409EFC" @click="switchAudio">
        <i-ep-VideoPlay v-if="!isAudioStart" />
        <i-ep-VideoPause v-else />
      </el-icon>
      <el-icon class="icon" :size="playIconSize" color="#409EFC" @click="nextAudio">
        <i-ep-CaretRight />
      </el-icon>
    </div>
    <div class="control">
      {{ currentTime }} / {{ duration }}
      <el-icon class="icon" :size="15" color="#409EFC" @click="playModelSwitch">
        <i-ep-Switch v-if="playModeValue == 'inorder'" />
        <i-ep-RefreshLeft v-else />
      </el-icon>
      <el-icon
        class="icon"
        :size="15"
        color="#409EFC"
        @click="
          () => {
            showVolume = !showVolume;
          }
        ">
        <i-ep-Bell />
        <div class="volume-box" v-show="showVolume">
          <el-slider
            v-model="volumeValue"
            size="small"
            vertical
            height="100px"
            @change="volumeChange" />
        </div>
      </el-icon>
    </div>
  </div>
  <audio
    ref="audio"
    :src="musicUrl"
    @canplay="getDuration"
    @timeupdate="timeUpdate"
    @ended="playModel">
    您的浏览器暂不支持audio
  </audio>
</template>

<script setup lang="ts">
  import { ref, onBeforeMount, watch, nextTick } from 'vue';
  import { getMusicToplist, getTopDetaliList, getMusicDetail } from '@/apis/music';
  const playIconSize = 20;
  /* 榜单和列表展示 */
  const musicMenuList: Ref<any[]> = ref([]);
  const musicMenuDetailList: any = ref([]);
  let currentMusicMenu: any = ref({});
  let currentMusic = ref({} as any);
  let currentIndex = ref(0);

  let detailParam = {
    id: currentMusicMenu.value.id,
    limit: 30,
    offset: 0
  };
  onBeforeMount(async () => {
    const res = await getMusicToplist();
    musicMenuList.value = res.list;
    currentMusicMenu.value = musicMenuList.value[0];
    detailParam.id = currentMusicMenu.value.id;
    await getTopDetaliListFun();
    currentMusic.value = musicMenuDetailList.value[0];
    currentIndex.value = 0;
    getMusicDetailFun();
  });
  // 获取榜单对应列表
  let isScroll = true;
  const getTopDetaliListFun = async () => {
    const { songs } = await getTopDetaliList(detailParam);
    musicMenuDetailList.value = [...musicMenuDetailList.value, ...songs];
    isScroll = true;
    if (songs.length == 0) isScroll = false;
  };
  // 获取对应歌曲
  const musicUrl = ref('');
  const getMusicDetailFun = async () => {
    try {
      const res: any = await getMusicDetail({ id: currentMusic.value.id });
      musicUrl.value = res.data[0].url;
    } catch (error) {
      console.error(error);
    }
  };
  // 点击榜单
  const goMenuMusicInfo = (item: any) => {
    currentMusicMenu.value = currentMusicMenu.value = item;
    detailParam.offset = 0;
    currentIndex.value = 0;
    detailParam.id = currentMusicMenu.value.id;
    musicMenuDetailList.value = [];
    getTopDetaliListFun();
  };
  // 滚动加载歌曲列表
  const detailList = ref(); // 获取目标元素
  const handleScroll = () => {
    if (
      detailList.value.clientHeight + detailList.value.scrollTop >=
      detailList.value.scrollHeight - 5
    ) {
      if (!isScroll) return;
      isScroll = false;
      detailParam.offset = detailParam.offset + detailParam.limit;
      getTopDetaliListFun();
    }
  };

  /* 音乐播放相关 */
  const audio = ref();
  const isAudioStart = ref(false);
  // 播放按钮
  const play = () => {
    // getMusicDetailFun();
    audio.value.play();
  };
  const switchAudio = () => {
    if (!isAudioStart.value) {
      audio.value.play();
    } else {
      audio.value.pause();
    }
    isAudioStart.value = !isAudioStart.value;
  };
  // 上一首
  const prevAudio = () => {
    if (currentIndex.value == 0) {
      currentIndex.value = musicMenuDetailList.value.length - 1;
    } else {
      currentIndex.value--;
    }
    audioPlay(musicMenuDetailList.value[currentIndex.value], currentIndex.value);
  };
  // 下一首
  const nextAudio = () => {
    if (currentIndex.value == musicMenuDetailList.value.length - 1) {
      currentIndex.value = 0;
    } else {
      currentIndex.value++;
    }
    audioPlay(musicMenuDetailList.value[currentIndex.value], currentIndex.value);
  };
  // 点击歌曲播放音乐
  const audioPlay = async (item: any, index: number) => {
    currentIndex.value = index;
    currentMusic.value = item;
    await getMusicDetailFun();
    isAudioStart.value = true;
    nextTick(() => {
      play();
    });
  };
  // 音量调节
  let volumeValue = ref(30);
  const showVolume = ref(false);
  const volumeChange = (val: number) => {
    volumeValue.value = val;
    audio.value.volume = volumeValue.value / 100;
  };

  // 获取时长
  const currentTime = ref('00:00');
  const duration = ref('00:00');
  const progressValue = ref(0);
  const progressMax = ref(0);
  const getDuration = () => {
    audio.value.volume = volumeValue.value / 100;
    let time = parseInt(audio.value.duration);
    progressMax.value = time;
    duration.value = toTime(time);
  };
  const toTime = (sec: number) => {
    let s = sec % 60 < 10 ? '0' + (sec % 60) : sec % 60;
    let min = Math.floor(sec / 60) < 10 ? '0' + Math.floor(sec / 60) : Math.floor(sec / 60);
    return min + ':' + s;
  };
  const timeUpdate = () => {
    let time = parseInt(audio.value.currentTime);
    progressValue.value = time;
    currentTime.value = toTime(time);
  };
  const progressChange = (val: number) => {
    audio.value.pause();
    audio.value.currentTime = val;
    audio.value.play();
    isAudioStart.value = true;
  };
  // 播放模式切换
  const playModeValue = ref('inorder');
  const playModelSwitch = () => {
    if (playModeValue.value == 'inorder') {
      playModeValue.value = 'loop';
    } else {
      playModeValue.value = 'inorder';
    }
  };
  // 播放方式 下一首 或 循环播放
  const playModel = () => {
    // 如果当前模式是循环播放
    if (playModeValue.value == 'loop') {
      audio.value.pause();
      // 将当前的播放时间置为0即可从头开始
      audio.value.currentTime = 0;
      audio.value.play();
    } else {
      // 否则调用切换下一首的函数
      nextAudio();
    }
  };
  // 监听 获取歌曲详情
  // const currentSong = ref({});
  const currentName = ref('');
  const currentAuth = ref('');
  const currentImg = ref('');
  watch(currentMusic, (v: any) => {
    currentImg.value = v.al.picUrl;
    currentName.value = v.name;
    currentAuth.value = v.ar[0].name;
  });
</script>

<style scoped lang="scss">
  .box {
    height: calc(100% - 135px);
    color: var(--text-color);
    padding-top: 20px;
    padding-bottom: 30px;
    margin-bottom: 0;
  }
  .music-menu {
    // min-height: 500px;
    max-height: calc(100% - 30px);
    overflow-y: auto;
    .menu-item {
      margin-right: 15px;
      margin-top: 10px;
      cursor: pointer;
    }
    img {
      width: 80px;
      height: 80px;
    }
  }
  .music-menu-list {
    max-height: calc(100% - 80px);
    // min-height: 500px;
    overflow-y: auto;
    padding: 0 15px;
    box-sizing: border-box;
    .music-list {
      font-size: 14px;
      margin-bottom: 15px;
      .music-name {
        cursor: pointer;
      }
      .music-name:hover {
        color: green;
      }
      .music-icon {
        width: 40px;
        padding-left: 20px;
        box-sizing: border-box;
      }
    }
  }
  .progress-bar {
    margin-top: -10px;
    margin-bottom: -10px;
  }

  .audio-box {
    height: 60px;
    font-size: 13px;
    background-color: var(--bg-color);
    color: var(--text-color);
    display: flex;
    justify-content: center;
    padding: 0 10px;
    margin: 0 auto 20px;
    div {
      flex: 1;
    }

    .audio-info {
      display: flex;
      align-items: center;
      font-size: 12px;
      overflow: hidden;
      img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-right: 10px;
      }
      .info {
        flex: 1;
        overflow: hidden;
      }
    }
    .play {
      flex: none;
      width: 100px;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      .icon {
        cursor: pointer;
        margin: 0 5px;
        position: relative;
      }
    }
    .control {
      display: flex;
      align-items: center;
      justify-content: right;

      .icon {
        margin-left: 5px;
        cursor: pointer;
      }
      .volume-box {
        position: absolute;
        bottom: 20px;
      }
    }
  }
  .imgRotate {
    animation: rotate 5s linear infinite;
  }
  @keyframes rotate {
    0% {
      transform: rotate(-180deg);
    }
    50% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(180deg);
    }
  }
</style>
